﻿using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Threading;
using IdentityAtRest.Utility.Identity;

namespace IdentityAtRest.Service.WcfExtensions
{
    public class ClaimsAuthContextInitializer : ICallContextInitializer
    {


        #region ICallContextInitializer Members

        public Object BeforeInvoke(InstanceContext instanceContext,
                                   IClientChannel channel,
                                   Message message)
        {
            DetectCurrentUser();
            return null;
        }

        public void AfterInvoke(Object correlationState)
        {
        }

        #endregion

        private static void DetectCurrentUser()
        {
            if (WebOperationContext.Current == null)
                throw new InvalidOperationException("Only HTTP web requests are supported for this version of the IPM API");

            string authToken = WebOperationContext.Current
                .IncomingRequest
                .Headers[AuthenticationHelper.AUTH_TOKEN_HEADER_NAME];

            if (AuthenticationHelper.SetCurrentUserFromAuthToken(authToken) == false)
            {
                Thread.CurrentPrincipal = null;
                //Currently, we'll allow anonymouse users. To forbid anonymous users entirley,
                //uncomment the following lines of code.

                //WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
                //throw new UnauthorizedAccessException(
                //    "No authentication token was found in the headers of the current request.");
            }
        }
    }
}